package cn.zh.boottinytomcat.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhanghuan
 * @date: 2022/9/5 21:37
 * @description: create it
 */

@Configuration
public class TomcatConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${server.additionalPorts}")
    private String additionalPorts;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        Connector[] additionalTomcatConnectors = getAdditionalConnectors();
        factory.addAdditionalTomcatConnectors(additionalTomcatConnectors);
    }

    private Connector[] getAdditionalConnectors() {
        if (StringUtils.isEmpty(additionalPorts)) {
            return null;
        }
        String[] ports = additionalPorts.split(",");
        List<Connector> connectors = new ArrayList<>();
        for (String port : ports) {
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(Integer.parseInt(port));
            connector.setScheme("http");
            connectors.add(connector);
        }
        // list 转数组
        return connectors.toArray(new Connector[]{});
    }

}
